Skip to content

Conversation

@Laphatize
Copy link
Member

No description provided.

@vercel
Copy link

vercel bot commented May 23, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
ctfguide-next ❌ Failed (Inspect) May 23, 2024 4:10am

@sweep-ai-deprecated
Copy link

sweep-ai-deprecated bot commented May 23, 2024

Sweep: PR Review

Authors of pull request: @SteveStef, @Laphatize

.env.development

Added a new environment variable NEXT_PUBLIC_GOOGLE_CLIENT_ID for Google service integrations.


src/components/AuthPopup.jsx

Removed Firebase authentication logic, causing the component to always display the "User logged out" state.

Sweep Found These Issues

  • The removal of the useEffect hook and Firebase authentication logic causes the component to always render the "User logged out" state, making it non-functional for authenticated users.
  • //import { getAuth, onAuthStateChanged } from 'firebase/auth';
    export function AuthPopup() {
    // check if firebase logged in
    const [user, setUser] = useState(false);
    if (user) {
    return <div>{/*User logged in*/}</div>;
    } else {
    // User logged out
    return (
    <div className="hidden rounded-md bg-[#3B82F6] hover:bg-[#468dff]">
    <Link href="/login">
    <div className="mx-auto my-auto flex h-10 text-center">
    <h1 className="mx-auto my-auto text-lg font-semibold text-white">
    Log in to see your progress!
    </h1>
    </div>
    </Link>
    </div>
    );
    }
    }

    View Diff


src/components/StandardNav.jsx

Removed Firebase authentication and replaced the logout mechanism with cookie manipulation and router redirection.

Sweep Found These Issues

  • The removal of the signOut(auth) method eliminates error handling during the logout process, which could lead to unhandled errors if the logout fails.
  • const [points, setPoints] = useState('0');
    const [notifications, setNotifications] = useState([]);
    const [showBanner, setShowBanner] = useState(false);

    View Diff


src/components/groups/assignments/create-challenge.jsx

Replaced Firebase authentication with JWT token authentication using cookies.

Sweep Found These Issues


src/components/groups/assignments/updateChallengeInfo.jsx

Replaced Firebase authentication with JWT-based authentication by modifying import statements and token retrieval logic.

Potential Issues

Sweep isn't 100% sure if the following are issues or not but they may be worth taking a look at.

  • The removal of Firebase authentication and replacement with JWT token decoding from cookies may introduce issues if the 'idToken' cookie is not set or is invalid, leading to potential authentication failures.
  • import request, { getCookie } from '@/utils/request';
    import { jwtDecode } from 'jwt-decode';
    const Editor = (props) => {
    const [contentPreview, setContentPreview] = useState('');
    const [penalty, setPenalty] = useState([0, 0, 0]);
    const [hints, setHints] = useState([
    'No hints set',
    'No hints set',
    'No hints set',
    ]);
    const [solution, setSolution] = useState('');
    const [difficulty, setDifficulty] = useState('');
    const [category, setCategory] = useState([]);
    const [newChallengeName, setNewChallengeName] = useState(props.title);
    const [errMessage, setErrMessage] = useState('');
    const [penaltyErr, setPenaltyErr] = useState('');
    const [username, setUsername] = useState('anonymous');
    const [existingFiles, setExistingFiles] = useState([]);
    const [existingConfig, setExistingConfig] = useState('');
    const [newConfig, setNewConfig] = useState('');
    const [selectedFile, setSelectedFile] = useState(null);
    const [isCreating, setIsCreating] = useState(false);
    const [classCode, setClassCode] = useState("");
    const [assignmentName, setAssignmentName] = useState("");
    const [viewCreateAssignment, setViewCreateAssignment] = useState(false);
    const validateNewChallege = async () => {
    for (const p of penalty) {
    if (p > 0) {
    toast.error('Please enter negative values for the points');
    return false;
    }
    }
    setPenaltyErr('');
    return true;
    };
    const sendToFileApi = async () => {
    if(!validateNewChallege()) {
    return;
    }
    const cookie = getCookie('idToken');
    const data = jwtDecode(cookie);
    const token = data.id;

    View Diff

  • The jwtDecode function is used without proper error handling, which could cause the application to crash if the cookie is malformed or the token is invalid.
  • const cookie = getCookie('idToken');
    const data = jwtDecode(cookie);
    const token = data.id;

    View Diff


src/components/onboarding/DataAsk.jsx

Simplified the logout function, modernized the HTTP request to use Fetch API, and improved code readability and maintainability through various formatting changes.


src/components/onboarding/OnboardingFlow.jsx

Modified OnboardingFlow to accept props and updated DataAsk rendering to include email, password, and accountType props.

Sweep Found These Issues

  • If props.email, props.password, or props.accountType are undefined or null, it could lead to potential runtime errors or unexpected behavior in the DataAsk component.
  • export function OnboardingFlow(props) {
    const router = useRouter();
    const [flowState, setFlowState] = useState(router.query.part || '1');
    var username = '';
    var birthday = '';
    var firstname = '';
    var lastname = '';
    var location = '';
    useEffect(() => {
    setFlowState(router.query.part);
    }, [router.query.part]);
    if (flowState === '1') {
    return <DataAsk email={props.email} password={props.password} accountType={props.accountType}/>;
    } else if (flowState === '2') {
    return <DataAskPart2 />;
    } else if (flowState === '3') {
    return <Demo />;
    } else {
    return <DataAsk email={props.email} password={props.password} accountType={props.accountType}/>;
    }

    View Diff


src/components/studio/forking/editor.jsx

Switched authentication from Firebase to JWT tokens stored in cookies.

Sweep Found These Issues

  • The new method of obtaining the token from a cookie and decoding it introduces a potential security vulnerability if the cookie is not securely managed or if the JWT decoding is not properly validated.
  • if(!validateNewChallege()) {
    return;
    }
    const cookie = getCookie('idToken');
    const data = jwtDecode(cookie);
    const token = data.id;

    View Diff


src/config/firebaseConfig.js

Removed the Firebase configuration and initialization code by deleting firebaseConfig.js.

Sweep Found These Issues

  • Removing the Firebase configuration and initialization code will break any functionality dependent on Firebase services, as the app will no longer be initialized.
  • /*
    © CTFGuide Corporation
    */
    import { initializeApp } from 'firebase/app';
    //import { getAnalytics } from "firebase/analytics";
    /*
    This code is intended to be public. This is public facing client information.
    It isn't some secret key or anything. It's just a way for our auth service (Firebase) to identify the app.
    */
    //
    const firebaseConfig = {
    apiKey: process.env.NEXT_PUBLIC_APP_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_APP_AUTH_DOMAIN,
    projectId: process.env.NEXT_PUBLIC_APP_PROJECT_ID,
    storageBucket: process.env.NEXT_PUBLIC_APP_STORAGE_BUCKET,
    messagingSenderId: process.env.NEXT_PUBLIC_APP_MESSAGING_SENDER_ID,
    appId: process.env.NEXT_PUBLIC_APP_ID,
    measurmentId: process.env.NEXT_PUBLIC_APP_MEASURMENT_ID,
    };
    //console.log(firebaseConfig);
    // Initialize Firebase
    // const app = initializeApp(firebaseConfig);
    // const firebaseConfig = {
    // apiKey: "AIzaSyBLAN84VP3jSA5dqhrU6Bjmfu5NiUDuNw4",
    // authDomain: "cyberjags-8b081.firebaseapp.com",
    // databaseURL: "https://cyberjags-8b081.firebaseio.com",
    // projectId: "cyberjags-8b081",
    // storageBucket: "cyberjags-8b081.appspot.com",
    // messagingSenderId: "166652277588",
    // appId: "1:166652277588:web:e08b9e19916451e14dcec1",
    // measurementId: "G-7ZNKM9VFN2"
    // };
    /**
    const firebaseConfig = {
    apiKey: 'AIzaSyBLAN84VP3jSA5dqhrU6Bjmfu5NiUDuNw4',
    authDomain: 'cyberjags-8b081.firebaseapp.com',
    databaseURL: 'https://cyberjags-8b081.firebaseio.com',
    projectId: 'cyberjags-8b081',
    storageBucket: 'cyberjags-8b081.appspot.com',
    messagingSenderId: '166652277588',
    appId: '1:166652277588:web:e08b9e19916451e14dcec1',
    measurementId: 'G-7ZNKM9VFN2',
    };
    */
    const app = initializeApp(firebaseConfig);
    // make a function to check if the cookie exists
    // if it does, then set the auth token to the cookie
    // Initialize Firebase
    //const analytics = getAnalytics(app);

    View Diff


src/config/jwt.js

Removed the entire JWT configuration and token management functionality from src/config/jwt.js.

Potential Issues

Sweep isn't 100% sure if the following are issues or not but they may be worth taking a look at.

  • The removal of the JWT configuration and token management functionality may break authentication features if they are not replaced or relocated elsewhere in the codebase.
  • import '@/config/firebaseConfig';
    import { getAuth } from 'firebase/auth';
    const auth = getAuth();
    const checkAuthToken = () => {
    const cookies = document.cookie.split(';').map(cookie => cookie.trim().split('=')[0]);
    return cookies.includes('idToken');
    }
    const updateAuthToken = async (auth) => {
    try {
    if(auth.currentUser && checkAuthToken()) {
    console.log("Generating new token");
    const idToken = await auth.currentUser.getIdToken(true);
    document.cookie = `idToken=${idToken}; SameSite=None; Secure; Path=/`;
    }
    } catch(err) {
    console.log(err);
    }
    }
    const updateAuthTokenInterval = (auth) => {
    const intervalId = setInterval(() => {
    updateAuthToken(auth);
    }, 10 * 60 * 1000);
    return () => {
    clearInterval(intervalId);
    };
    }
    updateAuthTokenInterval(auth);

    View Diff


src/config/lessonConfigs.js

Added a newline character at the end of the file for proper formatting.


src/middleware.js

Removed two unnecessary blank lines in middleware.js.


src/pages/_app.jsx

Integrated Google OAuth by wrapping the main component with GoogleOAuthProvider and removed JWT configuration import.

Potential Issues

Sweep isn't 100% sure if the following are issues or not but they may be worth taking a look at.

  • The GoogleOAuthProvider requires a valid client ID from environment variables, which could cause runtime errors if the environment variable is not set or is incorrect.
  • return <GoogleOAuthProvider clientId={process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID} scope="email profile openid">

    View Diff


src/pages/create/new.jsx

Replaced Firebase authentication with cookie-based JWT decoding for token retrieval in file uploads.

Potential Issues

Sweep isn't 100% sure if the following are issues or not but they may be worth taking a look at.

  • The code assumes that the 'idToken' cookie is always present and valid, which could lead to runtime errors if the cookie is missing or malformed.
  • const cookie = getCookie('idToken');
    const data = jwtDecode(cookie);
    const token = data.id;

    View Diff

  • The code assumes that the 'idToken' cookie is always present and valid, which could lead to runtime errors if the cookie is missing or malformed.
  • const cookie = getCookie('idToken');
    const data = jwtDecode(cookie);
    const token = data.id;

    View Diff

  • The jwtDecode function is used without validation, which could lead to security vulnerabilities if the token is tampered with.
  • const data = jwtDecode(cookie);
    const token = data.id;

    View Diff

  • The jwtDecode function is used without validation, which could lead to security vulnerabilities if the token is tampered with.
  • const data = jwtDecode(cookie);
    const token = data.id;

    View Diff


src/pages/login.jsx

Replaced Firebase authentication with custom API calls and integrated Google login using @react-oauth/google.

Sweep Found These Issues

  • Sweep has identified a redundant function: The new function handleLogin is redundant because its purpose and functionality are already covered by the existing handleLoginRequest function in src/pages/login.jsx.
  • const handleLogin = async (e) => {
    e.preventDefault();
    const requestOptions = {
    method: 'POST',
    body: JSON.stringify({ email, password, accountType: 'EMAIL'}),
    headers: { 'Content-Type': 'application/json' }
    };
    await handleLoginRequest(requestOptions);
    }

    View Diff

  • Sweep has identified a redundant function: The new function handleSuccess is redundant as its functionality is already covered by the existing handleSuccess function in src/pages/register.jsx.
  • async function handleSuccess(data) {
    console.log("Setting account by google");
    const { credential } = data;
    const decode = jwtDecode(credential);
    const { email } = decode;
    const requestOptions = {
    method: 'POST',
    body: JSON.stringify({ email, password: null, accountType: 'GOOGLE'}),
    headers: { 'Content-Type': 'application/json' }
    };
    await handleLoginRequest(requestOptions);
    }

    View Diff

  • Sweep has identified a redundant function: The new function handleError is redundant because its purpose and functionality are already covered by the existing handleError function in src/pages/register.jsx.
  • async function handleError(data) {
    console.log(data);
    toast.error('Google login failed. Please try again later.');
    }

    View Diff

Potential Issues

Sweep isn't 100% sure if the following are issues or not but they may be worth taking a look at.

  • The handleLoginRequest function does not handle non-200 HTTP responses properly, which could lead to unhandled errors.
  • async function handleLoginRequest(requestOptions) {
    setIsLoading(true);
    try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/account/login`, requestOptions);
    let data = await response.json();
    let { success, token, body } = data;
    if (success) {
    document.cookie = `idToken=${token}; SameSite=None; Secure; Path=/`;
    localStorage.setItem('username', body.username);
    localStorage.setItem('firstname', body.firstName);
    localStorage.setItem('lastname', body.lastName);
    localStorage.setItem('birthday', body.birthday);
    router.push('/dashboard');
    } else {
    toast.error(data.message);
    }
    } catch(error) {
    console.log(error);
    }
    setIsLoading(false);

    View Diff


src/pages/register.jsx

Replaced Firebase authentication with custom email existence check and Google OAuth login, updated registration form validation, and added conditional rendering for onboarding flow.

Sweep Found These Issues

  • The registerUser function incorrectly checks if an email exists by expecting a false response for an existing email, which is the opposite of the intended logic.
  • async function registerUser(e) {
    setAccountType('EMAIL');
    e.preventDefault();
    if(email == "" || password == "" || cpassword == "") {
    toast.error('Please fill in all fields.');
    return;
    }
    if(password.length < 8) {
    toast.error('Password must be at least 8 characters long.');
    return;
    }
    if (document.getElementById('password').value !== document.getElementById('cpassword').value) {
    toast.error('Passwords do not match.');
    return;
    }
    const exists = await emailExists(email);
    if(!exists) {
    toast.error('Email already exists.');
    return;
    }
    setShowOnboarding(true);
    console.log('Registering user...');
    }

    View Diff

  • Sweep has identified a redundant function: The new function registerUser is redundant as its purpose and functionality are already covered by the existing Register function and its associated handlers in src/pages/register.jsx.
  • async function registerUser(e) {
    setAccountType('EMAIL');
    e.preventDefault();
    if(email == "" || password == "" || cpassword == "") {
    toast.error('Please fill in all fields.');
    return;
    }
    if(password.length < 8) {
    toast.error('Password must be at least 8 characters long.');
    return;
    }
    if (document.getElementById('password').value !== document.getElementById('cpassword').value) {
    toast.error('Passwords do not match.');
    return;
    }
    const exists = await emailExists(email);
    if(!exists) {
    toast.error('Email already exists.');
    return;
    }
    setShowOnboarding(true);
    console.log('Registering user...');
    }

    View Diff

  • Sweep has identified a redundant function: The new function handleSuccess is redundant as its purpose and functionality are already covered by the existing handleSuccess function in src/pages/login.jsx.
  • async function handleSuccess(data) {
    console.log("Setting account by google");
    setAccountType('GOOGLE');
    const { credential } = data;
    const decode = jwtDecode(credential);
    setEmail(decode.email);
    const exists = await emailExists(decode.email);
    if(!exists) {
    toast.error('Email already exists.');
    return;
    }
    setPassword('');
    setShowOnboarding(true);
    }

    View Diff

  • Sweep has identified a redundant function: The new function handleError is redundant as its purpose and functionality are already covered by the existing handleError function in src/pages/login.jsx.
  • async function handleError(data) {
    console.log(data);
    toast.error('Account failed to create.');
    }

    View Diff

Potential Issues

Sweep isn't 100% sure if the following are issues or not but they may be worth taking a look at.

  • The registerUser function does not set isLoading to true, which could lead to user confusion during the registration process.
  • async function registerUser(e) {
    setAccountType('EMAIL');
    e.preventDefault();
    if(email == "" || password == "" || cpassword == "") {
    toast.error('Please fill in all fields.');
    return;
    }
    if(password.length < 8) {
    toast.error('Password must be at least 8 characters long.');
    return;
    }
    if (document.getElementById('password').value !== document.getElementById('cpassword').value) {
    toast.error('Passwords do not match.');
    return;
    }
    const exists = await emailExists(email);
    if(!exists) {
    toast.error('Email already exists.');
    return;
    }
    setShowOnboarding(true);
    console.log('Registering user...');
    }

    View Diff

  • The handleSuccess function does not reset the isLoading state, potentially causing the loading spinner to persist indefinitely.
  • async function handleSuccess(data) {
    console.log("Setting account by google");
    setAccountType('GOOGLE');
    const { credential } = data;
    const decode = jwtDecode(credential);
    setEmail(decode.email);
    const exists = await emailExists(decode.email);
    if(!exists) {
    toast.error('Email already exists.');
    return;
    }
    setPassword('');
    setShowOnboarding(true);
    }

    View Diff


src/pages/settings.jsx

Commented out Firebase storage and authentication functionalities, and replaced Firebase password update logic with an API request in the saveSecurity function.

Sweep Found These Issues

    Potential Issues

    Sweep isn't 100% sure if the following are issues or not but they may be worth taking a look at.


      src/pages/users/[user].jsx

      Removed Firebase storage functionalities and the user login status check, and cleaned up unused imports and blank lines.

      Sweep Found These Issues

      • The removal of the useEffect hook that checks if the user is logged in means the application no longer verifies the user's login status, which could lead to unauthorized access to certain parts of the application.
      • fetchData();
        }, [user]);
        // Follower useEffect
        useEffect(() => {
        if (!user) {
        return;
        }
        const fetchData = async () => {
        try {
        const endPoint =
        process.env.NEXT_PUBLIC_API_URL + '/followers/' + user + '/followers';
        const result = await request(endPoint, 'GET', null);
        const isFollower = result.followers.some(
        (followers) => followers.username == localStorage.getItem('username')
        );
        setFollowerCount(result.followers.length);
        setFollowedUser(isFollower);
        } catch (err) {
        invalidUser = true;
        }
        };

        View Diff


      The following files were not reviewed because our filter identified them as typically non-human-readable or less important files (e.g., dist files, package.json, images). If this is an error, please let us know.

      • package.json
      • yarn.lock

      @Laphatize Laphatize deleted the feat-auth-frontend branch August 1, 2024 15:42
      Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

      Labels

      None yet

      Projects

      None yet

      Development

      Successfully merging this pull request may close these issues.

      3 participants